<?php
  // S'assure que l'utilisateur est loggé (sinon, expédié en page d'accueil)
  gatekeeper();

  // S'assure que l'action est sécurisée
  action_gatekeeper();

  $ca = get_input('ca');
  $cr = get_input('cr');
  $parentGUID = get_input('parentGUID');
  
  $parent = get_entity($parentGUID);
  $parentTitle = $parent->title;
  $diag = "Diagnostic de compétence de ".$_SESSION['user']->name." pour le référentiel ".$parentTitle;
  
  // Cache to the session
  $_SESSION['diagnostic'] = $diag;
  
  
  // Make sure the title / description aren't blank
  if (empty($parentGUID)) {
    register_error(elgg_echo("pel:blank"));
    forward("mod/pel/addlang.php");
  }
  else {
    // Initialise a new ElggObject
    $diagnostic = new ElggObject();
    // Tell the system it's a diagnostic
    $diagnostic->subtype = "diagnostic";
    // Set its owner to the current user
    $diagnostic->owner_guid = $_SESSION['user']->getGUID();

    // Set its parent
    $diagnostic->container_guid = $parentGUID;
    
    // Set its description appropriately
    $diagnostic->description = $diag;
    
    // Before we can set metadata, we need to save the blog post
    if (!$diagnostic->save()) {
      register_error(elgg_echo("Vous ne pouvez pas enregistrer le diagnostic"));
      forward("mod/referential/index.php");
    }
    
    $diagnostic->ca = json_encode($ca);
    $diagnostic->cr = json_encode($cr);
        
    // Success message
    system_message(elgg_echo("Diagnostic sauvegardé."));
    // Remove the blog post cache
    unset($_SESSION['diagnostic']);
    // Forward to the main blog page
    forward("mod/referential/?user=" . $_SESSION['user']->username);
  }
?>